/*
 * @FilePath: ol.js
 * @Author: jzb
 * @Date: 2023-11-06 10:38:13
 * @LastEditors: Please set LastEditors
 * @LastEditTime: 2023-12-01 10:21:57
 * @Descripttion: 
 */

// openlayer封装类

import "ol/ol.css";
import Map from "ol/Map";
import View from "ol/View";
import Feature from 'ol/Feature'
import Point from 'ol/geom/Point'
import VectorLayer from "ol/layer/Vector";
import VectorSource from "ol/source/Vector";

import {
	circular
} from 'ol/geom/Polygon';

import {
	fromLonLat,
	Projection
} from "ol/proj";

import {
	Style,
	Circle,
	Fill,
	Stroke
} from "ol/style";

import Icon from "ol/style/Icon";
import {
	Overlay
} from "ol";
import {
	ScaleLine,
	defaults as defaultControls
} from 'ol/control';


import LayerManager from "./layers/LayerManager.js";
import Measure from './measure/measure.js'

export default class ol {
	/**
	 * 地图对象
	 */
	map;
	/**
	 * 图层
	 */
	LayerManager;
	/**
	 * 底图图层
	 */
	baseMapLayer;
	/**
	 * 地图中心
	 */
	center;
	/**
	 * 地图gps源
	 */
	locationSource;
	ydlayer;
	/**
	 * 测量
	 * @param {Object} options
	 */
	measure;

	/**
	 * 
	 */
	popue;

	constructor(options) {
		let {
			container,
			center
		} = options
		this.center = center
		this.LayerManager = new LayerManager(this.map)
		this.LayerManager.initBaseLayer(options.baselayer)


		this.baseMapLayer = this.LayerManager.baseLayers
		this.init(container)

	}


	// initBdMap(){
	//  var projBD09 = new	Projection({
	// 	        code: 'BD:09',
	// 	        extent: [-20037726.37, -11708041.66, 20037726.37, 12474104.17],
	// 	        units: 'm',
	// 	        axisOrientation: 'neu',
	// 	        global: false
	// 	    }

	// }

	/**
	 * 初始化地图
	 * @param {*} container 
	 */

	init(container) {
		let locationLayer = this.locationLayer()
		let layer = this.dataYdLayer()
		this.map = new Map({
			target: container,
			layers: [
				...this.baseMapLayer,
			
				locationLayer,
				layer
			],
			view: new View({
				projection: "EPSG:3857",
				center: fromLonLat(this.center),
				zoom: 13,
				minZoom: 2,
				maxZoom: 17
			}),
			controls: defaultControls({
				zoom: false,
				rotate: false,
				attribution: false
			})

			// .extend([
			// 	new ScaleLine({
			// 		//设置比例尺单位，degrees、imperial、us、nautical、metric（度量单位）
			// 		units: "metric"
			// 	})
			// ])
		});
		console.log("1c", container, this.map)
		this.LayerManager.setMap(this.map)

	}
	addLayers(arrs) {
		this.LayerManager.addLayers(arrs)
	}
	locationLayer() {
		this.locationSource = new VectorSource()
		const layer = new VectorLayer({
			id:"location",
			name:"location",
			source: this.locationSource
		});
		return layer
	}
	dataYdLayer() {
		let vector = new VectorSource()
		this.ydlayer = new VectorLayer({
			id:"yd",
			name:"yd",
			source: vector
		});
		return this.ydlayer
	}
	getLayer(name) {
		if (!this.LayerManager) {
		
			return null
		}
		if (this.LayerManager.layers) {
			if (this.LayerManager.layers[name]) {
				
				console.log("mm", this.LayerManager.layers[name])
				return this.LayerManager.layers[name]
			} else {
				console.log("ll")
				return this.ydlayer
			}
		} else {
			console.log("ss")
			return null
		}
	}
	/**
	 * 注册地图事件
	 * @param {*} enentType 
	 * @param {*} callback 
	 */
	registerClickEvent(enentType, callback) {
		this.map.on(enentType, (e) => {
			const pixel = this.map.getEventPixel(e.originalEvent)
			const currentFeature = this.map.forEachFeatureAtPixel(pixel, function(feature,
				layer) {
					// if(layer.getProperties().id!=='yd'){
						// return null;
					// }else{
						return feature
					// }

				

			})
			if(currentFeature){callback(currentFeature)}
			
		})
	}
	registerEvent(enentType, callback) {
		this.map.on(enentType, callback)
	}
	updateLoaction(pos, imageUrl) {
		const coords = [pos.longitude, pos.latitude];
		const accuracy = circular(coords, 25);
		this.locationSource.clear(true);

		let feature = new Feature(new Point(fromLonLat(coords)))
		let style = this.getStyleByImageurl(imageUrl)

		feature.setStyle(style)
		this.locationSource.addFeatures([
			new Feature(accuracy.transform('EPSG:4326', this.map.getView().getProjection())),
			feature
		]);

	}
	/**
	 * 
	 * @param {*} layerinfo 
	 */
	addProjectLayer(layerinfo) {
		let layer = this.LayerManager.initWMSLayer(layerinfo)
		this.map.addLayer(layer)
		setTimeout(() => {
			// this.map.getView().fit(layer.getSource().tmpExtent_)
			this.map.getView().setZoom(17)
		}, 1000);

	}
	addFeatureLayer(layerinfo) {
		let layer = this.LayerManager.initFeatureLayer(layerinfo)
		this.map.addLayer(layer)
	}
	getStyleByImageurl(url) {
		let style = new Style({
			image: new Icon({
				src: url,
				scale: 0.6,
				size: [75, 75]
			})
		})
		return style

	}
	clearPoints(layer) {
		layer.getSource().clear()
	}
	/**
	 * 渲染点要素
	 * @param {Object} layer
	 * @param {Object} coor[x,y]
	 * @param {Object} imageUrl
	 * @param {Object} id
	 * @param {Object} properties {}
	 */
	renderPoint(layer, coor, imageUrl, id, properties) {
	

		let epsg3857Coordinate = fromLonLat(coor);
		let geometry = new Point(epsg3857Coordinate)
		let style = this.getStyleByImageurl(imageUrl)
		let feature = new Feature({
			geometry

		})


		var pointStyle = new Style({
			image: new Circle({
				radius: 10,
				fill: new Fill({
					color: 'red'
				}),
				stroke: new Stroke({
					color: 'white',
					width: 2
				})
			})
		});

		feature.setStyle(style);
		feature.setProperties(properties)
		feature.setId(id)
		layer.getSource().addFeature(feature)
		

	}

	showPopue(options) {
		if (this.popue) {
			this.closePopue()
		}
		this.popue = new Overlay({
			element: options.element,
			positioning: 'bottom-center',
			stopEvent: false,
			offset: [0, 0],
			position: options.position
		})
		this.map.addOverlay(this.popue)
	}
	zoomToLayer(layer) {
		if (layer) {
			let extent = layer.getSource().getExtent()
			this.map.getView().fit(extent)
		}

	}
	zoomToLocation() {
		let extent = this.locationSource.getExtent()
		console.log(extent)
		this.map.getView().fit(extent)
	}
	closePopue() {
		if (this.popue) {
			this.map.removeOverlay(this.popue)
			this.popue = null
		}
	}
	zoomIn() {
		let view = this.map.getView();
		// 让地图的zoom增加1，从而实现地图放大
		view.setZoom(view.getZoom() + 1);
	}
	zoomOut() {
		let view = this.map.getView();
		// 让地图的zoom增加1，从而实现地图放大
		view.setZoom(view.getZoom() - 1);
	}
	measureLength() {
		if (!this.measure) {
			this.measure = new Measure(this.map)

		}
		this.measure.measureLength()
	}
	measureArea() {
		if (!this.measure) {
			this.measure = new Measure(this.map)

		}
		this.measure.measureArea()
	}
	measureClear() {
		if (this.measure) {
			this.measure.clear()

		}
	}
	destroy() {
		if (this.measure) {
			this.measure.destroy()
		}

	}

}